package com.sifang.POI.dianping;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

public class AddDistrictCommand implements Command {
	
	private Map<Integer, String> idMap = new HashMap<Integer, String>();
	private int cityId;
	private int count;
	
	public AddDistrictCommand(int cityId) {
		super();
		this.setCityId(cityId);
	}
	
	@Override
	public void execute() throws Exception {
		constructIdMap();
		Session s = DpDb.getInstance().openSession();
		List<Shop> list = getNextBatch(s);
		while (list != null && list.size() > 0) {
			s.beginTransaction();
			for (Shop shop : list) {
				String district = this.idMap.get(shop.getDistrictId());
				if (district == null) {
					district = "-";
					System.out.println(String.format("\nno district id: %d", shop.getShopId()));
				}
				shop.setDistrict(district);
				s.update(shop);
			}
			s.getTransaction().commit();
			System.out.print(String.format("\r%d processd", count += list.size()));
			list = getNextBatch(s);
		}
		s.close();
	}

	@SuppressWarnings("unchecked")
	private List<Shop> getNextBatch(Session s) {
		String query = "from Shop shop where shop.district is null";
		return s.createQuery(query).setMaxResults(1000).list();
	}

	private void constructIdMap() throws IOException, XPatherException {
		TagNode node = WebUtil.cleanUrl(String.format("http://www.dianping.com/shopall/%d/0", getCityId()));
		Object[] results = node.evaluateXPath("//div[@class='box shopallCate'][2]//a[@class='Bravia']");
		for (Object result : results) {
			node = (TagNode) result;
			String href = node.getAttributeByName("href");
			int id = Integer.parseInt(href.substring(href.lastIndexOf('r') + 1));
			String text = node.getText().toString();
			this.idMap.put(id, text);
		}
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		new AddDistrictCommand(288).execute();
	}

	public int getCityId() {
		return cityId;
	}

	public void setCityId(int cityId) {
		this.cityId = cityId;
	}
	
	@Override
	public String toString() {
		return this.getClass().getName();
	}

}
